﻿using AuthCenter.Domain;
using AuthCenter.ErorCode;
using AuthCenter.Infrastructure;
using AuthCenter_API.Write.Applications.Commands.RBAC;
using AutoMapper;
using MediatR;

namespace AuthCenter_API.Write.Applications.CommandHandlers.RBAC
{
    public class MenuDelCommandHandler : IRequestHandler<MenuDelCommand, APIResult<object>>
    {
        private readonly IBaseRepository<MenuModel> _menuRepository;
        private readonly IMapper _mapper;

        public MenuDelCommandHandler(IBaseRepository<MenuModel> menuRepository, IMapper mapper)
        {
            _menuRepository = menuRepository;
            _mapper = mapper;
        }

        public async Task<APIResult<object>> Handle(MenuDelCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Code = APIEnum.DelSuccess;
            result.Message = APIEnum.DelSuccess.Desc();
            var m=_menuRepository.GetAll().FirstOrDefault(x=>x.MenuId==request.MenuId);
            if (m!=null)
            {
                result.Code = APIEnum.DelSuccess;
                result.Message = APIEnum.DelSuccess.Desc();
                m.IsDel = 1;
                Del(m.MenuId);
                await _menuRepository.Update(m);
            }
            return await Task.FromResult(result);
        }
        public string Del(int MenuId)
        {
            List<MenuModel> menus=_menuRepository.GetAll().Where(x=>x.PID==MenuId).ToList();
            if (menus != null)
            {
                foreach (var item in menus)
                {
                    item.IsDel = 1;
                    Del(item.MenuId);
                }
            }
            return "删除成功";
        }
    }
}
